<div class="row">
    <div class="col-md-12">
        <div id="buttonBar" class="box-widget">
            <button id="addBuyDialog" class="btn btn-success">
                Bán hàng
            </button>
        </div>
        <div class="box-widget">
            <table id="list-group" class="table data-tbl-boxy responsive">
                <thead>
                    <tr>
                        <th id="stt">#</th>
                        <th id="date" class="text-center">
                            Ngày
                        </th>
                        <th id="name" class="text-center">
                            Tên khách hàng
                        </th>
                        <th id="sale" class="text-center">
                            Bán hàng
                        </th>
                        <th id="buy" class="text-center">
                            Nợ cũ
                        </th>
                        <th id="payment" class="text-center">
                            Đã thanh toán
                        </th>
                        <th id="payment" class="text-center">
                            Còn lại
                        </th>
                        <th>
                            Xóa
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                        $i = 0;
                        $total = 0;
                        $totalDept = 0;
                        $totalPayment = 0;
                        $totalRemaining = 0;
                    ?>
                    <?php foreach($this->data as $row): ?>
                    <?php
                        $i ++;
                        $class = "";
                        
                        if($row['remaining'] == 0){
                            $class = "zero";
                        }
                        
                        $total += $row['total'];
                        $totalDept += $row['dept'];
                        $totalPayment += $row['totalpay'];
                        $totalRemaining += $row['remaining'];
                    ?>
                    <tr id="row" class="<?php echo $class; ?>">
                        <td class="text-center">
                            <?php echo $i; ?>
                            
                        </td>
                        <td class="text-center">
                            <?php echo date("d-m-Y", strtotime($row['date'])); ?>
                        </td>
                        <td>
                            <?php echo $row['name']; ?>
                        </td>
                        <td class="text-right">
                            <?php echo number_format($row['total'], 0, null, "."); ?>
                        </td>
                        <td class="text-right">
                            <?php echo number_format($row['dept'], 0, null, "."); ?>
                        </td>
                        <td class="text-right">
                            <?php if($row['receiver'] != null) echo "<strong>" . $row['receiver'] . "</strong>: "; ?>
                            <?php echo number_format($row['totalpay'], 0, null, "."); ?>
                        </td>
                        <td class="text-right">
                            <?php echo number_format($row['remaining'], 0, null, "."); ?>
                        </td>
                        <td id="tool">
                            <a id="editData" class="btn btn-mini btn-info" href="">
                                Sửa
                            </a>
                            <a id="deleteData" class="btn btn-mini btn-danger" href="">
                                Xóa
                            </a>
                            <input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" class="text-right">
                            <strong>
                                Tổng cộng:
                            </strong>
                        </td>
                        <td class="text-right">
                            <strong>
                                <?php echo number_format($total, 0, null, "."); ?>
                            </strong>
                        </td>
                        <td class="text-right">
                            <strong>
                                <?php echo number_format($totalDept, 0, null, "."); ?>
                            </strong>
                        </td>
                        <td class="text-right">
                            <strong>
                                <?php echo number_format($totalPayment, 0, null, "."); ?>
                            </strong>
                        </td>
                        <td class="text-right">
                            <strong>
                                <?php echo number_format($totalRemaining, 0, null, "."); ?>
                            </strong>
                        </td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
<div id="add-buy" title="Nhập bán hàng" class="form-horizontal form-box"> 
    <form id="add-buy-form">
        <div class="form-group">
            <label class="col-lg-4 control-label">Tên khách hàng</label>
            <div class="col-lg-7">
                <select class="form-control" name="name">
                    <?php foreach($this->customers as $row): ?>
                    <option value="<?php echo $row->id; ?>"><?php echo $row->name; ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="button" id="addCustomer" class="btn btn-mini btn-success"> Thêm </button> 
                <button type="button" id="deleteCustomer" class="btn btn-mini btn-danger"> Xóa </button>
            </div>
        </div>
        <div class="form-group">
            <label class="col-lg-4 control-label">Số tiền</label>
            <div class="col-lg-7">
                <input class="form-control" type="text" name="total" value="" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-lg-4 control-label">Thanh toán</label>
            <div class="col-lg-7">
                <input class="form-control" type="text" name="totalpay" value="" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-lg-4 control-label">Tài khoản</label>
            <div class="col-lg-7">
                <input class="form-control" type="text" name="receiver" value="" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-lg-4 control-label">Nợ cũ</label>
            <div class="col-lg-7">
                <input class="form-control" readonly="" type="text" name="dept" value="" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-lg-4 control-label">Còn lại</label>
            <div class="col-lg-7">
                <input class="form-control" readonly="" type="text" name="remaining" value="" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-lg-4 control-label">Ngày</label>
            <div class="col-lg-7">
                <input type="text" class="form-control" id="datepicker" name="date" value="<?php echo date("d-m-Y"); ?>" />
                <input type="hidden" name="type" value="0" />
            </div>
        </div>
    </form>
</div>
<div id="add-customer" title="Thêm khách hàng">
    <form id="add-customer-form">
        Tên khách hàng<br />
        <input type="text" name="name" id="name" /><br />
        Điện thoại<br />
        <input type="text" value="" name="phone_number" id="phone_number" /><br />
        Địa chỉ<br />
        <input type="text" value="" name="address" id="address" />
        <input type="hidden" value="0" name="discount_type" id="discount_type" />
        <input type="hidden" value="0" name="discount_value" id="discount_value" />
        <input type="hidden" name="type" id="type" value="0" /> 
    </form>
</div>
<script>
function ajaxLoading(){
    var html = '<div class="imgLoading">';
    html += '<img class="imgLoading" src="<?php echo $this->templateURL; ?>/images/ajax-loader/ajax-loader_orange.gif" />';
    html += '</div>';
    
    $("body").append(html);
}

function deleteRow(id){
    var ok = confirm("Bạn muốn xóa dòng này?");
    
    if(ok){
        $.ajax({
            url: "<?php echo $this->url(array('module' => 'admin', 'controller' => 'log', 'action' => 'delete'), null, true); ?>",
            data: {"id": id},
            beforeSend: ajaxLoading(),
            success: function (result){
                //$("div.imgLoading").remove();
                location.reload(); 
            }
        });
    }
}

$(document).ready(function(){
    $(window).scroll(function(){
        if($(this).scrollTop() > 0){
            $("#buttonBar").addClass("fixed");
            $("#list-group_wrapper").addClass("fixed");
            $(".widget-head").addClass("fixed");
            $("table#list-group").addClass("fixed");
        }else{
            $("#buttonBar").removeClass("fixed");
            $("#list-group_wrapper").removeClass("fixed");
            $(".widget-head").removeClass("fixed");
            $("table#list-group").removeClass("fixed");
        }
    });
    
    $("body").on("click", "ul.pagination li", function(){
        $(window).scrollTop(0);
    });
    
    $("#list-group").on("page.dt", function(){
        $(window).scrollTop(0);
    });
    
    var optionNumeric = {'aSep': '.', 'aDec': ',', 'mDec': 0, 'vMin': 0, 'vMax': 999999999999, 'wEmpty': 'zero'};
    var optionNumeric1 = {'aSep': '.', 'aDec': ',', 'mDec': 0, 'vMin': -999999999999, 'vMax': 999999999999, 'wEmpty': 'zero'};
    $("input[name='total'], input[name='totalpay']").autoNumeric('init', optionNumeric);
    $("input[name='remaining'], input[name='dept']").autoNumeric('init', optionNumeric1);
    
    var dialogBuy = $("div#add-buy").dialog({
        autoOpen: false,
        height: 520,
        width: 450,
        modal: true,
        buttons: {
            "Thêm": addBuy,
            Cancel: function(){
                dialogBuy.dialog("close");
            }
        },
        close: function(){
            $("form#add-buy-form").trigger("reset");
        }
    });
    
    var dialogCustomer = $("div#add-customer").dialog({
        autoOpen: false,
        height: 350,
        width: 300,
        modal: true,
        buttons: {
            "Thêm": addCustomer,
            Cancel: function(){
                dialogCustomer.dialog("close");
            }
        },
        close: function(){
            $("form#add-customer-form").trigger("reset");
        }
    });
    
    $("button#addBuyDialog").click(function(){
        $("select[name='name']").removeAttr("disabled");
        $("select[name='name'] option[selected='selected']").removeAttr("selected");
        dialogBuy.dialog("open");
    });
    
    $("button#addCustomer").click(function(){
        $("form#add-customer-form input#type").val(0);
        dialogCustomer.dialog("open");
    })
    
    $("button#deleteCustomer").click(function(){
        var ok = confirm("Bạn muốn xóa khách hàng này?");
        
        if(ok){
            var customer_id = $(this).parent("div.col-lg-7").children("select[name='name']").val();
            var selectBox = $(this).parent("div.col-lg-7").children("select[name='name']");
            var url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'customer', 'action' => 'delete-ajax'), null, true); ?>";
            
            $.ajax({
                url: url,
                data: {'customer_id' : customer_id},
                type: "POST",
                beforeSend: ajaxLoading(),
                success: function(result){
                    $(selectBox).children("option[value='" + customer_id + "']").remove();
                    $("div.imgLoading").remove();
                }
            });
        }
    });
    
    function addCustomer(){
        var type = $("form#add-customer-form input#type").val();
        
        type = parseInt(type);
        
        var url = "";
        
        if(type == 0){
            url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'customer', 'action' => 'create-ajax'), null, true) ?>";
        }else{
            url = "<?php echo $this->url(array('module' => 'admin', 'controller' => 'supplier', 'action' => 'create-ajax'), null, true) ?>";
        }
        
        var name = $("form#add-customer-form input#name").val();
        var phone_number = $("form#add-customer-form input#phone_number").val();
        var address = $("form#add-customer-form input#address").val();
        
        $.ajax({
            url: url,
            data: {'name': name, 'phone_number': phone_number, 'address': address, 'discount_type': 0, 'discount_value': 0},
            beforeSend: ajaxLoading(),
            success: function (result){
                var obj = $.parseJSON(result);
                
                $("div.imgLoading").remove();
                
                if(obj.error == false){
                    var customer = obj.data;
                    var html = '<option value="' + customer.id + '">' + customer.name + '</option>';
                    
                    if(type == 0){
                        $("form#add-buy-form select[name='name']").append(html);
                        $("form#add-buy-form select[name='name'] option[value='" + customer.id + "']").attr("selected", "selected");
                        $("form#add-buy-form select[name='name'] option[value='" + customer.id + "']").prop("selected", true);
                    }else{
                        $("form#add-sale-form select[name='name']").append(html);
                        $("form#add-sale-form select[name='name'] option[value='" + customer.id + "']").attr("selected", "selected");
                        $("form#add-sale-form select[name='name'] option[value='" + customer.id + "']").prop("selected", true);
                    }
                    
                    dialogCustomer.dialog("close");
                }else{
                    var html = '<span id="customer-error" style="color: red;">';
                    html += obj.message.name;
                    html += '</span>';
                    html += '<br />';
                    
                    $("form#add-customer-form").before(html);
                }
            }
        });
    }
    
    function addBuy(){
        var name = $("form#add-buy-form select[name='name']").val();
        var date = $("form#add-buy-form input[name='date']").val();
        var total = $("form#add-buy-form input[name='total']").autoNumeric('get');
        var totalpay = $("form#add-buy-form input[name='totalpay']").autoNumeric('get');
        var receiver = $("form#add-buy-form input[name='receiver']").val();
        var dept = $("form#add-buy-form input[name='dept']").autoNumeric('get');
        var remaining = $("form#add-buy-form input[name='remaining']").autoNumeric('get');
        var id = $("form#add-buy-form input[name='id']").val();
        
        if(id == null){
            id = 0;
        }
        
        $.ajax({
            url: "<?php echo $this->url(array('module' => 'admin', 'controller' => 'sale-total', 'action' => 'add'), null, true); ?>",
            data: {'id': id, 'name': name, 'date': date, 'total': total, 'totalpay': totalpay, 'receiver': receiver, 'dept': dept, 'remaining': remaining},
            beforeSend: ajaxLoading(),
            success: function(result){
                $("div.imgLoading").remove();
                window.location.reload();
                //alert(result);
            }
        });
    }
    
    var optionDatePicker = {
        changeMonth: true,
        changeYear: true,
        dateFormat: "dd-mm-yy",
    };
     
    $.datepicker.regional["vi-VN"] =
    {
        closeText: "Đóng",
        prevText: "Trước",
        nextText: "Sau",
        currentText: "Hôm nay",
        monthNames: ["Tháng một", "Tháng hai", "Tháng ba", "Tháng tư", "Tháng năm", "Tháng sáu", "Tháng bảy", "Tháng tám", "Tháng chín", "Tháng mười", "Tháng mười một", "Tháng mười hai"],
        monthNamesShort: ["Một", "Hai", "Ba", "Bốn", "Năm", "Sáu", "Bảy", "Tám", "Chín", "Mười", "Mười một", "Mười hai"],
        dayNames: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"],
        dayNamesShort: ["CN", "Hai", "Ba", "Tư", "Năm", "Sáu", "Bảy"],
        dayNamesMin: ["CN", "T2", "T3", "T4", "T5", "T6", "T7"],
        weekHeader: "Tuần",
        dateFormat: "dd/mm/yy",
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ""
    };
     
    $.datepicker.setDefaults($.datepicker.regional["vi-VN"]);
    
    $( "input#datepicker" ).datepicker(optionDatePicker);
    
    function getDept(){
        var customer_id = $("select[name='name']").val();
        var date = $("#datepicker").val();
        var id = $("form#add-buy-form input[name='id']").val();
        
        if(id == null){
            id = 0;
        }
        
        $.ajax({
            url: "<?php echo $this->url(array('module' => 'admin', 'controller' => 'sale-total', 'action' => 'get-dept'), null, true); ?>",
            data: {'customer_id': customer_id, 'date': date, 'order_id': id},
            success: function(result){
                $("form#add-buy-form input[name='dept']").autoNumeric('set', result);
                remaining();
                //alert(id);
            }
        });
    }
    
    getDept();
    
    function remaining(){
        var total = $("form#add-buy-form input[name='total']").autoNumeric('get');
        var totalpay = $("form#add-buy-form input[name='totalpay']").autoNumeric('get');
        var dept = $("form#add-buy-form input[name='dept']").autoNumeric('get');
        
        total = parseInt(total);
        totalpay = parseInt(totalpay);
        dept = parseInt(dept);
        
        var remaining = total + dept - totalpay;
        
        $("form#add-buy-form input[name='remaining']").autoNumeric('set', remaining);
    }
    
    $("input#datepicker, select[name='name'], input[name='total'], input[name='totalpay']").change(function(){
        getDept();
        remaining();
    });
    
    $("a#deleteData").click(function(){
        var ok = confirm("Bạn muốn xóa dòng này?");
        
        if(ok){
            var id = $(this).parent("td#tool").children("input[name='id']").val();
            
            $.ajax({
                url: "<?php echo $this->url(array('module' => 'admin', 'controller' => 'sale-total', 'action' => 'delete'), null, true); ?>",
                data: {'id': id},
                beforeSend: ajaxLoading(),
                success: function(result){
                    result = parseInt(result);
                    
                    if(result >= 0){
                        window.location.reload();
                    }else{
                        alert("Lỗi");
                    }
                    
                    $("div.imgLoading").remove();
                }
            });
        }
        
        return false;
    });
    
    $("a#editData").click(function(){
        var id = $(this).parent("td#tool").children("input[name='id']").val();
        
        $.ajax({
            url: "<?php echo $this->url(array('module' => 'admin', 'controller' => 'sale-total', 'action' => 'get-data'), null, true); ?>",
            data: {'id': id},
            beforeSend: ajaxLoading(),
            success: function(result){
                var order = $.parseJSON(result);
                
                if(order.error == false){
                    $("form#add-buy-form select[name='name']").attr("disabled", "disabled");
                    $("form#add-buy-form select[name='name']").children("option[selected='selected']").removeAttr("selected");      
                    $("form#add-buy-form select[name='name'] option[value='" + order.data.name + "']").attr("selected", "selected");
                    $("form#add-buy-form select[name='name'] option[value='" + order.data.name + "']").prop("selected", true);
                    $("form#add-buy-form input[name='total']").autoNumeric('set', order.data.total);
                    $("form#add-buy-form input[name='totalpay']").autoNumeric('set', order.data.totalpay);
                    
                    $("form#add-buy-form input[name='receiver']").val(order.data.receiver);
                    
                    $("form#add-buy-form input[name='dept']").autoNumeric('set', order.data.dept);
                    $("form#add-buy-form input[name='remaining']").autoNumeric('set', order.data.remaining);
                    
                    var date = order.data.date;
                    var arrDate = date.split("-");
                    var newDate = arrDate[2] + "-" + arrDate[1] + "-" + arrDate[0];
                    $("form#add-buy-form input[name='date']").val(newDate);
                    
                    var html = '<input type="hidden" value="' + order.data.id + '" name="id" />';
                    $("form#add-buy-form input[name='date']").after(html);
                    
                    dialogBuy.dialog("open");
                }else{
                    alert("Lỗi");
                }
                
                $("div.imgLoading").remove();
            }
        });
        
        return false;
    });
});

$(function() {
    var table = $('.data-tbl-boxy').dataTable({
        "sPaginationType": "bootstrap",
        "bSort": true,
        "fnDrawCallback": function(){
            $(window).scrollTop(0);
        },
        "iDisplayLength": 10,
        "oLanguage": {
            "sLengthMenu": "<span class='lengthLabel pull-left'><?php echo $this->translate('entries_per_page'); ?>:</span><span class='lenghtMenu pull-left'> _MENU_</span>",
            "sInfo": "<?php echo $this->translate('show start end records of total'); ?>",
            "sSearch": "<?php echo $this->translate('filter'); ?>:",
            "oPaginate": {
                "sFirst": "<?php echo $this->translate('first page'); ?>",
                "sLast": "<?php echo $this->translate('last page'); ?>",
                "sNext": "<?php echo $this->translate('next page'); ?>",
                "sPrevious": "<?php echo $this->translate('previous page'); ?>"
            }
        },
        "sDom": '<"widget-head clearfix"fl>,<"widget-container"<"widget-block"<"widget-content"t>,,<"table-bottom clearfix"<"tbl-pagination pull-left"p><"tbl-data-info pull-right"i>>',
    });
});
</script>
<style>
.ui-dialog{
    position: fixed;
}

.page-header{
    display: none;
}

tr.zero td{
    font-weight: bold;
}

tr.zero td:last-child{
    color: red;
}

#buttonBar{
    margin-top: 10px;
    background-color: transparent;
    box-shadow: none;
}

div.imgLoading{
    width: 100%;
    height: 100%;
    top:  0;
    left:  0;
    bottom:  0;
    right:  0;
    background-color: #000000;
    opacity: 0.7;
    position: fixed;
    z-index: 3;
}

img.imgLoading{
    position: fixed;
    top: 50%;
    left: 50%;
    width: 40px;
    height: 40px;
    z-index: 3;
}
</style>